package com.speedy.course.ui

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.speedy.course.databinding.FragmentTaskBinding
import com.speedy.course.databinding.ItemTaskBinding
import com.speedy.course.db.entity.Task
import com.speedy.course.ext.withEmptyBody
import com.speedy.course.vm.TaskViewModel
import kotlinx.coroutines.launch

class TaskFragment : Fragment() {

    private var _binding: FragmentTaskBinding? = null

    private val binding get() = _binding!!

    private val viewModel by viewModels<TaskViewModel>()

    private val adapter:TaskAdapter = TaskAdapter()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        _binding = FragmentTaskBinding.inflate(inflater, container, false)

        _binding?.apply {
            recyclerView.adapter = adapter

            ivAdd.setOnClickListener {
                startActivity(Intent(activity,AddTaskActivity::class.java))
            }

            remindFrameLayout.setOnClickListener {
                startActivity(Intent(activity,AddTaskActivity::class.java))
            }

            remindFrameLayout.registerAdapterDataObserver(adapter)
        }

        return binding.root
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initObserver()

        viewModel.loadTaskList()
    }

    private fun initObserver() {
        lifecycleScope.launch { 
            viewModel.taskPageFlow.collect{
                adapter.submitData(it)
            }
        }
    }


    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}


private class TaskAdapter: PagingDataAdapter<Task,TaskViewHolder>(
    TaskDiff
){


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskViewHolder {
        val binding = ItemTaskBinding.inflate(LayoutInflater.from(parent.context),parent,false)
        return TaskViewHolder(binding)
    }

    override fun onBindViewHolder(holder: TaskViewHolder, position: Int) {
        holder.binding.task = getItem(position)
    }


}


private class TaskViewHolder(val binding: ItemTaskBinding) : RecyclerView.ViewHolder(binding.root){

}

object TaskDiff :DiffUtil.ItemCallback<Task>(){
    override fun areItemsTheSame(oldItem: Task, newItem: Task): Boolean {
        return oldItem == newItem
    }

    override fun areContentsTheSame(oldItem: Task, newItem: Task): Boolean {
        return oldItem.id == newItem.id
    }

}